#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import os
import time
from threading import current_thread
from concurrent.futures import ThreadPoolExecutor


def tesk(res):
    time.sleep(5)
    print("进程: {} 结果: {}".format(current_thread().name, res))
    return res ** 2

def parse(res):
    time.sleep(1)
    print("{} 处理的数据为: {}".format(current_thread().name,res.result()))


if __name__ == '__main__':
    pool = ThreadPoolExecutor(4)
    start = time.time()
    for i in range(1, 5):
        func = pool.submit(tesk, i)
        func.add_done_callback(parse)  # 回调函数,
            # func 添加回调函数,需要有一个返回值 return结果,将其结果丢给另一个函数处理
    pool.shutdown(wait=True)
    stop = time.time()

    print("master: {}, 时间: {}".format(current_thread().name, stop - start))
"""
    # 线程池 处理时间为 9.278696298599243, 哪个线程有空闲就会直接回调函数处理
    进程: ThreadPoolExecutor-0_0 结果: 1
    进程: ThreadPoolExecutor-0_1 结果: 2
    进程: ThreadPoolExecutor-0_3 结果: 4
    进程: ThreadPoolExecutor-0_2 结果: 3
    ThreadPoolExecutor-0_1 处理的数据为: 4
    ThreadPoolExecutor-0_0 处理的数据为: 1
    ThreadPoolExecutor-0_3 处理的数据为: 16
    ThreadPoolExecutor-0_2 处理的数据为: 9
    master: MainThread, 时间: 6.002583265304565
"""